package transport.route;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.swing.text.BadLocationException;
import javax.swing.text.StyleContext;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class RouteFinder {
	private HttpClient httpclient;
	private String filename;
	private String rounte_no;

	public RouteFinder() {
		this.httpclient = new DefaultHttpClient();
		rounte_no = "39a";
		filename = "route_" + rounte_no + ".txt";
	}

	public void getRouteData() throws ClientProtocolException, IOException,
			JSONException, BadLocationException {
		HttpGet httpget = new HttpGet("http://hittheroad.ie/bus/" + rounte_no);

		HttpResponse response = httpclient.execute(httpget);
		System.out.println(response.getProtocolVersion());
		System.out.println(response.getStatusLine().getStatusCode());
		System.out.println(response.getStatusLine().getReasonPhrase());
		System.out.println(response.getStatusLine().toString());

		HttpEntity entity = response.getEntity();
		if (entity != null) {
			InputStream instream = entity.getContent();
			try {

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(instream));
				// do something useful with the response
				System.out.println(reader.readLine());

				HTMLEditorKit kit = new HTMLEditorKit();
				HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
				doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
				kit.read(reader, doc, 0);
				StyleContext text = doc.getStyleSheet();
				String data = text.toString();
				int start = data.indexOf("var routes");
				int end = data.length();
				System.out.println(start);
				System.out.println(end);
				// System.out.println(data);
				String tmp = (String) data.subSequence(start, end);
				start = tmp.indexOf("[");
				end = tmp.indexOf("name=comment");
				String jsonString = (String) tmp.subSequence(start, end - 2);
				// System.out.println(jsonString);
				JSONArray jsondata = new JSONArray(jsonString);
				String[] strStops = null;
				// one route can have multiple route plans.
				System.out.println(jsondata.length());
				for (int i = 0; i < jsondata.length(); i++) {
					JSONObject obj = jsondata.getJSONObject(i);
					JSONArray stops = obj.getJSONArray("stops");
					strStops = convertJSONArray(stops);
					writeToFile(strStops);
				}
			} catch (IOException ex) {

				// In case of an IOException the connection will be released
				// back to the connection manager automatically
				throw ex;

			} catch (RuntimeException ex) {

				// In case of an unexpected exception you may want to abort
				// the HTTP request in order to shut down the underlying
				// connection and release it back to the connection manager.
				httpget.abort();
				throw ex;

			} finally {

				// Closing the input stream will trigger connection release
				instream.close();

			}

			httpclient.getConnectionManager().shutdown();

		}
	}

	private String[] convertJSONArray(JSONArray array) throws JSONException {
		String[] rtnArray = null;
		if (array != null) {
			rtnArray = new String[array.length()];
			for (int i = 0; i < array.length(); i++) {
				JSONObject jsonElem = array.getJSONObject(i);
				String lng = jsonElem.get("lng").toString();
				String lat = jsonElem.get("lat").toString();
				rtnArray[i] = lng + " " + lat;
				System.out.println(rtnArray[i]);
			}
		}
		return rtnArray;
	}

	private void writeToFile(String[] array) {
		try {
			BufferedWriter out = new BufferedWriter(new FileWriter(filename, true));
			for (int i = 0; i < array.length; i++) {
				out.write(array[i] + "\n");
			}
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	public static void main(String[] args) {
		RouteFinder rf = new RouteFinder();
		try {
			rf.getRouteData();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadLocationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
